package com.ken.common.event.plugins.idempotent.token;

import com.ken.common.event.framework.message.EventMessage;
import com.ken.common.event.framework.processor.SendMsgPostProcessor;
import com.ken.common.event.plugins.idempotent.token.constant.TokenConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnBean(TokenIdempotentHandler.class)
@Slf4j
public class TokenSendMsgPostProcessor implements SendMsgPostProcessor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean beforeProcessor(String eventTypeStr, EventMessage eventMessage) {
        log.debug("[Send-Msg] - Token发送消息前置处理器触发 - {}", eventMessage.getMsgId());
        String redisKey = TokenConstant.TOKEN_REDIS_PREFIX + eventMessage.getMsgId();
        if(!redisTemplate.hasKey(TokenConstant.TOKEN_REDIS_PREFIX + eventMessage.getMsgId())) {
            redisTemplate.opsForValue().set(redisKey, "0");
            log.debug("[Send-Msg] - 已将Token令牌设置到Redis上 - {}", eventMessage.getMsgId());
            return true;
        }
        return false;
    }
}
